import Router from "./../../router";
import store from "./../../store"; // 需要添加 vuex
// import { Toast } from 'vant'
import { MessageBox, Message } from "element-ui";
import axios from "axios";
import helper from "./helper";
import { getToken, removeToken } from "@/utils/auth";
let qs = require("querystring");

// success/warning/info/error
/**
 * 响应消息反馈
 */
const responseMsgType = {
  200: { msg: "成功", messageType: "success" },
  1002: { msg: "系统繁忙！", messageType: "error" },
  1003: { msg: "暂无数据！", messageType: "info" },
  1005: { msg: "请先登录", messageType: "warning" },
  1006: { msg: "账号或密码错误！", messageType: "warning" },
  1007: { msg: "参数格式错误", messageType: "warning" },
  1008: { msg: "查询失败", messageType: "error" },
  1009: { msg: "账号异常，请重新登录！", messageType: "warning" },
  1010: { msg: "网络繁忙，请稍后重试！", messageType: "error" },
};
/***
 * 需要重新登录的状态码
 */
const reLoginCode = [1005, 1006, 1009];
/**
 * 筛选空数据的状态码
 */
const successDataCodes = [ 1003, 1007]; 

// 引用axios，设置头文件
axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded";

// 添加请求拦截器
axios.interceptors.request.use(
  function (config) {
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
axios.interceptors.response.use(
  function (response) {
    /**
     * 下面的注释为通过在response里，自定义code来标示请求状态
     * 当code返回如下情况则说明权限有问题，登出并返回到登录页
     * 如想通过xmlhttprequest来状态码标识 逻辑可写在下面error中
     */

    return new Promise((resolve, reject) => {
      const msgCode = response.data.code;
      const resMsgType = responseMsgType[msgCode];
      // console.log(
      //   "=============================",
      //   resMsgType,
      //   msgCode,
      //   response
      // );
      Message({
        message: resMsgType.msg,
        type: resMsgType.messageType,
        duration: 5 * 1000,
      });
      if (msgCode == 200) {
        resolve(response.data);
      } else if (reLoginCode.includes(msgCode)) {
        // Message({
        //   message: "令牌失效需要重新登录",
        //   type: "warning",
        //   duration: 5 * 1000,
        // });
        let loginSta = removeToken();
        if (loginSta) {
          Router.push({ path: "/login" });
        } else {
          Message({
            message: "处理登录信息失败，请手动登录！",
            type: "warning",
            duration: 5 * 1000,
          });
        }
      } else if (successDataCodes.includes(msgCode)) {
        Message({
          message: response.data.msg,
          type: "info",
          duration: 5 * 1000,
        });
        resolve([]);
      } else {
        Message({
          message: response.data.msg,
          type: "error",
          duration: 5 * 1000,
        });
        resolve(response.data);
      }
    });
  },
  function (error) {
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

function apiAxios(method, url, params, ...args) {
  // console.log('apiAxios=>', store)
  let { headers, responseType, timeout } = args;

  let tempheaders = {
    "Content-Type": "application/json;charset=utf-8",
    token: getToken(),
  };
  if (headers && headers) {
    tempheaders = Object.assign({}, tempheaders, headers);
  }
  let option_ = {
    method: method,
    // 拼接参数
    url:
      method === "GET" || method === "DELETE"
        ? helper.queryString(url, params)
        : url,
    data: method === "POST" || method === "PUT" ? params : null,
    timeout: timeout,
    headers: tempheaders,
    withCredentials: false,
  };
  if (responseType && responseType) {
    option_["responseType"] = responseType;
  }
  return axios(option_);
}

export default {
  get: function (url, params, ...args) {
    return apiAxios("GET", url, params, ...args);
  },
  post: function (url, params, ...args) {
    return apiAxios("POST", url, params, ...args);
  },
  put: function (url, params, ...args) {
    return apiAxios("PUT", url, params, ...args);
  },
  delete: function (url, params, ...args) {
    return apiAxios("DELETE", url, params, ...args);
  },
};
